

from django import template
from django.db.models import Count

from ..models import Post, Category, Tag

# 1). 创佳模板标签库对象
register = template.Library()


# 2). 编写查询最新博客信息的函数，并添加到模板标签库中;
@register.simple_tag
def get_recent_posts(num=5):
    posts = Post.objects.all().order_by('-created_time')[:num]
    return  posts

# 归档的模板标签
@register.simple_tag
def archives():
    # <QuerySet [datetime.date(2020, 3, 1)]>
   dates = Post.objects.dates('created_time', 'month', order='DESC')
   return  dates


@register.simple_tag
def get_categories():
   # 别忘了在顶部引入 Category 类
   return Category.objects.all()

@register.simple_tag
def get_tags():
   return Tag.objects.all()

@register.simple_tag
def get_categories():
    # 记得在顶部引入 count 函数
    # Count 计算分类下的文章数,其接受的参数为需要计数的模型的名称
    return Category.objects.annotate(num_posts=Count('post')).filter(num_posts__gt=0)